package com.minjiang.blog.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 所有错误页面拦截
 * ControllerAdvice拦截所有标有controller的控制器
 */
@ControllerAdvice
public class ErrorController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * ModelAndView返回一个页面和后台的一些信息
     * @ExceptionHandler(Exception.class) Exception的级别的异常处理
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception {
        logger.error("Request URL : {}, Exception:{}",request.getRequestURI(),e);
        /**
         * 标识状态码的，交由spring自己处理即做逻辑的判断
         * 参数：异常类和状态类
         */
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null){
            //抛出异常交由spring自己处理
            throw e;
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURI());
        mv.addObject("exception",e);
        mv.setViewName("error/error");
        return mv;
    }
}
